<!--  -->
<template>
  <div>
    <el-button
      type="primary"
      style="display: flex; margin: 1rem 0"
      @click="centerDialogVisible = true"
      icon="el-icon-plus"
      >添加角色</el-button
    >
    <el-dialog
      title="添加角色"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
    >
      <el-form
        :model="AddForm"
        :rules="rules"
        ref="AddForm"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="RoleName">
          <el-input v-model="AddForm.RoleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="RoleDesc">
          <el-input v-model="AddForm.RoleDesc"></el-input>
        </el-form-item>
        <el-form-item label="权限等级" prop="PermissionLevel">
          <el-select
            v-model="AddForm.PermissionLevel"
            placeholder="请选择权限等级"
          >
            <el-option label="一级" value="1"></el-option>
            <el-option label="二级" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAddForm('AddForm')"
            >立即创建</el-button
          >
          <el-button @click="resetAddForm('AddForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-table
      :data="RightsTable"
      style="width: 100%; border-radius: 5px"
      border
    >
      <!-- 权限详情-懒加载 -->
      <el-table-column type="expand">
        <template slot-scope="props">
          <span style="margin: 0 1em">权限详情:</span>
          <!-- 一次性把权限标签全喷出来 -->
          <el-tag
            v-for="(p, idx) in ensureRights(props.row)"
            :key="idx"
            closable
            type="primary"
            style="margin-right: 5px"
            @close="handleRightRemove(props.row, idx)"
          >
            {{ p.label }}
          </el-tag>
          <!-- 如果二级什么都没有，给个提示 -->
          <el-tag
            v-if="getRightsByLevel(props.row.level).length === 0"
            type="info"
          >
            无权限
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column type="index" label="编号" width="150" align="center">
      </el-table-column>
      <el-table-column label="角色名称" width="150">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色描述" width="300">
        <template slot-scope="scope">
          <div slot="reference" class="name-wrapper">
            <el-tag size="medium">{{ scope.row.desc }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="权限等级" width="200">
        <template slot-scope="scope">
          <el-tag
            size="medium"
            :type="scope.row.level === '1' ? 'primary' : 'success'"
            >{{ scope.row.level + "级" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary">
            <!--
  1. @command 是 el-dropdown 的自定义事件，它只接收一个参数：被点菜单的 command 值
  2. 这里把 scope（行数据）和 $event（command 值）一起传进方法,通过changeLevel(scope, $event)方法调用表达式
  3. 顺序必须是：自定义参数在前，$event 在后，因为 $event 会被编译器替换成“事件源发出的唯一实参”
  -->
            <el-dropdown trigger="click" @command="changeLevel(scope, $event)">
              <span class="el-dropdown-link">
                修改权限等级<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="1">1级</el-dropdown-item>
                <el-dropdown-item command="2">2级</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="deleteTableColumn(scope.$index, scope.row)"
          >
            <i class="el-icon-delete btn-delete-icon">删除</i>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { cloneDeep } from "lodash"; // 安装lodash库
export default {
  name: "PermissionList",
  data() {
    return {
      assignPermissionForm: {},
      AddForm: {
        RoleName: "",
        RoleDesc: "",
        PermissionLevel: "",
      },
      dialogAssignPermission: false,
      centerDialogVisible: false,
      // 根据权限等级来定义分配权限,1.使用对象数组管理角色，2.通过对象数组中的权限等级来分配权限
      RightsTable: [
        { name: "小李", desc: "前端开发工程师", level: "1" },
        { name: "小何", desc: "服务器开发工程师", level: "1" },
        { name: "小王", desc: "软件测试工程师", level: "1" },
        { name: "小吴", desc: "客服", level: "1" },
        { name: "小张", desc: "HR", level: "2" },
      ],
      // 权限池
      PERMISSION_POOL: [
        { module: "user", label: "用户列表" },
        { module: "product", label: "基本表单" },
        { module: "product", label: "商品分类" },
        { module: "product", label: "商品列表" },
        { module: "rights", label: "权限管理" },
        { module: "order", label: "订单管理" },
      ],
      // 校验规则
      rules: {
        RoleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        RoleDesc: [
          { required: true, message: "请输入角色描述/职业", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        PermissionLevel: [
          { required: true, message: "请选择权限等级", trigger: "change" },
        ],
      },
    };
  },
  mounted() {},
  watch: {},
  methods: {
    // 权限详情：移除单个权限
    handleRightRemove(row, idx) {
      row._rights.splice(idx, 1); // 删掉指定下标那一条
    },
    // 第一次展开时把池子抄(复制)一份到行自身，起名叫 _rights（用 this.$set 保证 Vue 能跟踪到新增属性）,后面复用
    ensureRights(row) {
      // 如果该行还没挂过 _rights，就现场挂一个
      if (!row._rights) {
        // this.$set 让 Vue 把新增属性变成“响应式” this.$set(目标对象, '新增属性名', 属性值) 作用：“告诉 Vue，我现在要给这个目标对象加一个以前没有的新属性，请你一起把它变成响应式！”
        this.$set(row, "_rights", this.getRightsByLevel(row.level));
      }
      // 返回这个数组，供 v-for 使用
      return row._rights;
    },
    // 根据 level 返回当前角色应展示的权限数组
    getRightsByLevel(level) {
      return level === "1"
        ? this.PERMISSION_POOL // 一级全给
        : this.PERMISSION_POOL.filter((p) => p.module === "product").slice(
            0,
            1
          ); // 二级只给 1 个
    },
    // 添加角色确认按钮
    submitAddForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 声明一个变量，把添加角色界面收集的数据重新赋值，添加到列表中
          const addRole = {
            name: this.AddForm.RoleName,
            desc: this.AddForm.RoleDesc,
            level: this.AddForm.PermissionLevel,
          };
          this.RightsTable.push(addRole);
          this.$refs[formName].resetFields();
        } else {
          console.log("error submit!!");
          return false;
        }
        this.centerDialogVisible = false;
      });
    },
    // 添加角色重置按钮
    resetAddForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 删除功能
    deleteTableColumn(index, row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.RightsTable.splice(index, 1);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    changeLevel(scope, newLevel) {
      // 1. 改等级
      scope.row.level = newLevel;
      // 2. 删除旧权限缓存（Vue 会触发视图更新）this.$delete(obj目标对象, key要删除的键名)，等价于 Vue.delete(obj, key)
      this.$delete(scope.row, "_rights");
      //  另一种删除方案：直接清空数组（保留键）scope.row._rights.splice(0)
      // 或scope.row._rights.length = 0;
      // ensureRights 里 if (!row._rights) 会进不去，需要再加一个“长度为 0”的判断：if (!row._rights || row._rights.length === 0)
      // 3. 强制重新计算并缓存新权限
      this.ensureRights(scope.row);
      this.$message.success(`已设为 ${newLevel} 级`);
    },
    // 打开分配权限按钮
    openAssignPermission(index, row) {
      this.dialogAssignPermission = true;
    },
    // 修改分配权限确认按钮
    handleAssignPermission() {
      this.dialogAssignPermission = false;
      this.$message({
        message: "修改权限等级成功！",
        type: "success",
      });
    },
    // 取消修改分配权限
    CancelAssignPermission() {
      this.dialogAssignPermission = false;
      this.$message("取消修改权限等级！");
    },
  },
};
</script>
<style lang='scss' scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 100%;
}
.EditRole-body {
  text-align: left;
}
// 分配权限按钮样式
.el-dropdown-link {
  font-family: element-icons;
  font-size: 12px;
  cursor: pointer;
  color: #ffffff;
}
// 分配权限右侧箭头样式
.el-icon-arrow-down {
  font-size: 12px;
}
// 分配权限下拉菜单详情样式
.el-dropdown-menu__item {
  color: #333;
  font-size: 12px;
}
// 删除按钮调整高度
.btn-delete-icon {
  border: 1px solid transparent;
}
</style>